import os
import pandas as pd
from datetime import datetime
from collections import defaultdict
import threading
from openpyxl.styles import Alignment

class StatisticsService:
    def __init__(self, config, loggers):
        self.config = config
        self.model_config = config['model_check']
        self.loggers = loggers
        self.running = False
        self.stats_timer = None

    def start(self):
        """启动统计服务"""
        self.running = True
        self.loggers['info'].info("=== 启动统计服务 ===")
        
        # 创建必要的目录
        os.makedirs(self.model_config['output_dir'], exist_ok=True)
        os.makedirs(self.model_config['statistics_dir'], exist_ok=True)
        
        # 检查并执行统计
        if self.model_config['statistics']['enabled']:
            self.loggers['info'].info(
                f"统计功能已启用，模式: {self.model_config['statistics']['mode']}"
            )
            self.generate_statistics()

    def generate_statistics(self):
        """生成统计报告"""
        try:
            self.loggers['info'].info("\n" + "="*50)
            self.loggers['info'].info("开始生成统计报告")
            
            # 检查输出目录
            output_dir = self.model_config['output_dir']
            if not os.path.exists(output_dir):
                self.loggers['warn'].warning(f"输出目录不存在: {output_dir}")
                return
            
            # 获取所有CSV文件
            csv_files = []
            for root, _, files in os.walk(output_dir):
                csv_files.extend([os.path.join(root, f) for f in files if f.endswith('.csv')])
            
            total_files = len(csv_files)
            if total_files == 0:
                self.loggers['warn'].warning("未找到需要统计的CSV文件")
                return
            
            self.loggers['info'].info(f"开始处理 {total_files} 个CSV文件")
            
            # 初始化统计数据
            stats = defaultdict(lambda: {'LLM': 0, 'HUMAN': 0})
            
            # 处理文件
            for file_path in csv_files:
                try:
                    df = pd.read_csv(file_path)
                    model_field = self.model_config['result_fields'][1]  # 模型名称字段
                    category_field = self.model_config['result_fields'][2]  # 类别字段
                    
                    for _, row in df.iterrows():
                        model = row[model_field]
                        category = row[category_field]
                        if category in ['LLM', 'HUMAN']:
                            stats[model][category] += 1
                
                except Exception as e:
                    self.loggers['error'].error(f"处理文件失败: {file_path}, 错误: {str(e)}")
                    continue

            # 生成报告
            if stats:
                self._save_statistics(stats)
            
        except Exception as e:
            self.loggers['error'].error(f"生成统计报告失败: {str(e)}")
        finally:
            if self.running and self.model_config['statistics']['enabled']:
                interval = self.model_config['statistics']['interval']
                self.stats_timer = threading.Timer(interval, self.generate_statistics)
                self.stats_timer.start()

    def _save_statistics(self, stats):
        """保存统计结果"""
        try:
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            report_path = os.path.join(
                self.model_config['statistics_dir'],
                f'统计报告_{timestamp}.xlsx'
            )
            
            # 准备数据
            rows = []
            for model, counts in sorted(stats.items(), key=lambda x: (-x[1]['LLM'], x[0])):
                total = counts['LLM'] + counts['HUMAN']
                llm_ratio = (counts['LLM'] / total * 100) if total > 0 else 0
                rows.append({
                    '模型名称': model,
                    'LLM数量': counts['LLM'],
                    'HUMAN数量': counts['HUMAN'],
                    '总数': total,
                    'LLM占比': f"{llm_ratio:.2f}%"
                })

            # 创建DataFrame并保存为Excel
            df = pd.DataFrame(rows)
            writer = pd.ExcelWriter(report_path, engine='openpyxl')
            df.to_excel(writer, index=False, sheet_name='统计结果')
            
            # 设置格式
            worksheet = writer.sheets['统计结果']
            for column in worksheet.columns:
                max_length = max(len(str(cell.value)) for cell in column if cell.value)
                adjusted_width = min(max_length + 2, 20)
                worksheet.column_dimensions[column[0].column_letter].width = adjusted_width
            
            writer.save()
            self.loggers['info'].info(f"统计报告已保存: {report_path}")
            
        except Exception as e:
            self.loggers['error'].error(f"保存统计报告失败: {str(e)}")

    def stop(self):
        """停止统计服务"""
        self.running = False
        if self.stats_timer:
            self.stats_timer.cancel()  Statistics。p y